<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : UserToken.php
 * Created on : 2020-7-25 10:50:38
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\models;

use think\Model;
use app\models\User;

/**
 * 
 * Class UserToken
 * Tiger <1192851302@qq.com> 2020-7-25 10:50:38
 */
class UserToken extends Model {

    protected $name = 'user_token';

    /**
     * 创建token并且保存
     * @author Tiger <1192851302@qq.com>
     * @param User $user
     * @param $type
     * @return UserToken
     */
    public static function createToken(User $user, $type): self {
        $tokenInfo = $user->getToken($type);
        try {
            $token = self::where('user_id', $user->id)->find();
            if (empty($token)) {
                return self::create(['user_id' => $user->id, 'token' => $tokenInfo['token'], 'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp'])]);
            } else {
                $token->token = $tokenInfo['token'];
                $token->expires_time = date('Y-m-d H:i:s', $tokenInfo['params']['exp']);
                $token->save();
                return $token;
            }
        } catch (\Exception $exc) {
            exception($exc->getMessage());
        }
    }

    /**
     * 删除一天前的过期token
     * @author Tiger <1192851302@qq.com>
     * @return bool
     * @throws \Exception
     */
    public static function delToken() {
        return self::where('expires_time', '<=', date('Y-m-d H:i:s', strtotime('-1 day')))->delete();
    }

    /**
     * 
     * @author Tiger <1192851302@qq.com>
     * @param type $token
     * @return type
     */
    public static function parseToken($token) {
        if (empty($token)) {
            exception('参数错误,请重新登录', 410000);
        }
        $user_token = self::where('token', $token)->find();
        if (empty($user_token)) {
            exception('参数错误,请重新登录', 410000);
        }
        try {
            list($user, $type) = User::parseToken($token);
        } catch (\Throwable $e) {
            exception($e->getMessage() ?: '登录已过期,请重新登录', 410001);
        }

        if ($user['status'] == 1) {
            exception('已被锁定', 410003);
        }
        //输出最新的数据
        
        return [$user, $type];
    }

}
